/**
 * Created by sky on 2019/3/12.
 */
layui.define(['CommonSocket', 'CommonProtoBuf3', 'justchatProto', 'justchatModel','zepto'], function (exports) {
    var $ = layui.zepto;
    var CommonProtoBuf3 = layui.CommonProtoBuf3;
    var justchatProto = layui.justchatProto;
    var CommonSocket = layui.CommonSocket;
    var justchatModel = layui.justchatModel;
    var socketState = 'pending';
    var justchatSocketMgr = {
        justChatSocket: null,
        justChatSocketUrl: null,
        justChatProtoMgr: null,
        init: function (eventCallback) {
            var self = this;
            var msgType = justchatModel.obj_msg_type;
            if (self.justChatSocket == null) {
                self.justChatProtoMgr = new CommonProtoBuf3(justchatProto, 'justchatProto.proto', msgType);
                var msgCallback = function (protobufData) {
                    var message = self.justChatProtoMgr.decode(protobufData);
                    if (message && msgType[message.index]) {
                        if (typeof (eventCallback) == "function") {
                            eventCallback(message.index, message.msgData);
                        }
                    }
                };
                var initCallBack = function () {
                    self.pingSend();
                    self.authReqSend();
                };


                var websocketObj = {
                    onCloseCallback:function(){
                        socketState = 'close'
                        self.notifySocketStateChange()
                    },
                    onSuccessCallback:function(){
                        $(".justchat-status").html('');
                        window.parent.postMessage({type:'imStatus', status: 1},"*");
                        socketState = 'success'
                        self.notifySocketStateChange()
                    },
                    onReconnectCallback:function(){
                        socketState = 'reconnecting'
                        self.notifySocketStateChange()
                    }
                }

                self.justChatSocket = new CommonSocket("justchat", self.justChatSocketUrl, null, msgCallback, initCallBack,null,null,websocketObj);
            }
        },

        sendInTopicReq:function(id){
            var self = this;
            var data = {
                Topic: {
                    TOPIC_TYPE: 0,
                    ID: id
                }
            };
            self.send(3, "msg.InTopicReq", data);
        },

        notifySocketStateChange:function(){
            this.dep(socketState)
        },

        watchSocketState:function(fn){
            this.dep = fn
        },

        pingSend: function () {
            var self = this;
            var nowTimer = new Date().getTime();
            var data = {
                Timestamp: nowTimer
            };
            console.log("justchat=》Ping");
            self.send(0, "msg.Ping", data);
        },

        authReqSend: function () {
            var self = this;
            var token = self.getParam('token');
            if (token) {
                var data = {
                    Token: token.toString()
                };
                console.log("justchat=》authReq");
                self.send(1, "msg.AuthReq", data);
            }
        },

        getParam: function (paramName) {
            var paramValue = "", isFound = !1;
            if (window.location.search.indexOf("?") == 0 && window.location.search.indexOf("=") > 1) {
                var arrSource = unescape(window.location.search).substring(1, window.location.search.length).split("&"), i = 0;
                while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
            }
            return paramValue == "" && (paramValue = null), paramValue
        },

        send: function (sendId, msgType, data) {
            var self = this;
            console.log('sendId：'+sendId, msgType, data)
            var totalBuffer = self.justChatProtoMgr.encode(sendId, msgType, data);
            self.justChatSocket.send(totalBuffer);
        },

        close: function () {
            var self = this;
            if (self.justChatSocket != null) {
                self.justChatSocket.close();
                self.justChatSocket = null;
            }
        }
    };

    exports('justchatSocketMgr', justchatSocketMgr);
});
